// index.js
import{ preferentialList,recommendList,searchProduct} from "../../network/product";
import { getToken } from "../../utils/token";
import { getList } from "../../network/swipper";

Page({
  data:{
    pgoods:[],
    rgoods:[],
    key:undefined,
    search:[],
    swipList:[]
  },
  onLoad(options) {
    // 获取优惠商品信息
    preferentialList()
    .then(res => {
      this.setData({
        pgoods:res.data
      })
    })
    .catch(err => {
      wx.showToast({
        title: err.msg,
      })
    });
    // 获取推荐商品信息
    recommendList().then(res => {
      this.setData({
        rgoods:res.data
      })
    }).catch(err => {
      wx.showToast({
        title: err.msg,
      })
    })
  },
  onShow() {
    this.getSwipperList();
    // 获取优惠商品信息
    preferentialList()
    .then(res => {
      this.setData({
        pgoods:res.data
      })
    })
    .catch(err => {
      wx.showToast({
        title: err.msg,
      })
    });
    // 获取推荐商品信息
    recommendList().then(res => {
      this.setData({
        rgoods:res.data
      })
    }).catch(err => {
      wx.showToast({
        title: err.msg,
      })
    })
  },
  // 获取轮播图
  getSwipperList() {
    getList().then(res => {
      console.log(res)
      this.setData({
        swipList:res.data
      })
    })
  },
  // 监听用户输入
  keyCode(e) {
    this.setData({
      key:e.detail.value,
      search:[]
    })
  },
  // 搜索商品
  searchInfo() {
    searchProduct({
      name:this.data.key
    }).then(res => {
      this.setData({
        search:res.data
      })
    })
  },
  //失去焦点
  reset() {
    console.log('ll')
    this.setData({
      search:[]
    })
  }, 
  // 刷视频
  video() {
    wx.navigateTo({
      url: '/pages/video/video',
    })
  },
  // 分类
  category() {
    wx.navigateTo({
      url: '/pages/category/category',
    })
  },
  recommend() {
    wx.navigateTo({
      url: '/pages/recommend/recommend',
    })
  },
  preferential() {
    wx.navigateTo({
      url: '/pages/preferential/preferential',
    })
  },
  // 联系
  makePhone(e) {
    const token = getToken()
    if (token) {
      wx.makePhoneCall({
        phoneNumber: e.target.dataset.phone,
      })
    }else{
      wx.showToast({
        title: '请登录',
        icon:'error'
      })
    } 
  },
  // 商品详情
  productDetail(e) {
    let infoData = JSON.stringify(e.currentTarget.dataset.info)
    wx.navigateTo({
      url: `/pages/productDetail/productDetail?info=${encodeURIComponent(infoData)}`,
    })
  },
  onShareAppMessage() {}
})
